package cn.layfolk.seckill.web.controller;


import cn.hutool.json.JSONUtil;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import cn.layfolk.seckill.redis.SeckillRedisKey;
import cn.layfolk.seckill.service.TSeckillGoodsService;
import cn.layfolk.seckill.vo.SeckillGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/seckillGoods")
public class TSeckillGoodsController {

    private TSeckillGoodsService seckillGoodsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 优化前吞吐量1181.5
     * 优化后4817
     * 查询所有秒杀商品
     */
    @GetMapping("/query")
    public ResponseVo<?> query(){
        return ResponseVo.ok(seckillGoodsService.queryByCache());
    }

    //回显秒杀商品详情页
    @GetMapping("/{id}")
    public ResponseVo<?> findById(@PathVariable("id") Long id){
        return ResponseVo.ok(seckillGoodsService.findByIdInCache(id));
    }

    @GetMapping("/initData")
    public ResponseVo<?> initData() {
        List<SeckillGoodsVo> query = seckillGoodsService.query();
        for (SeckillGoodsVo seckillGoodsVo : query) {
            //数据预热，将所有秒杀的商品信息，缓存到Redis
            stringRedisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_GOODS_HASH.getRealKey(""),
                    seckillGoodsVo.getId()+"",
                    JSONUtil.toJsonStr(seckillGoodsVo) +"");

            // 将所有库存保存到redis中，数据预热
            stringRedisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(""),
                    seckillGoodsVo.getId()+"",
                    seckillGoodsVo.getStockCount()+"");
        }
        return ResponseVo.ok(null);
    }
}

